import React, { useState } from 'react';
import {
    Typography,
    Box,
    Container,
    Grid,
    Link,
    Alert,
    Snackbar
} from '@mui/material';
import {
    Email as EmailIcon,
    Person as PersonIcon,
    Lock as LockIcon
} from '@mui/icons-material';
import { motion } from 'framer-motion';
import { Link as RouterLink, useNavigate } from 'react-router-dom';

import FormInput from '../components/ui/FormInput';
import Button from '../components/ui/Button';
import AnimatedCard from '../components/ui/AnimatedCard';
import { useAuth } from '../contexts/AuthContext';

const Register = () => {
    const navigate = useNavigate();
    const { register, loading: authLoading } = useAuth();
    const [formData, setFormData] = useState({
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
    });

    const [errors, setErrors] = useState({});
    const [loading, setLoading] = useState(false);
    const [notification, setNotification] = useState({
        open: false,
        message: '',
        severity: 'info'
    });

    // 表单输入处理
    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value
        });

        // 清除该字段的错误
        if (errors[name]) {
            setErrors({
                ...errors,
                [name]: null
            });
        }
    };

    // 表单验证
    const validateForm = () => {
        const newErrors = {};

        // 用户名验证
        if (!formData.username.trim()) {
            newErrors.username = '用户名不能为空';
        } else if (formData.username.length < 3) {
            newErrors.username = '用户名至少需要3个字符';
        }

        // 邮箱验证
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!formData.email.trim()) {
            newErrors.email = '邮箱不能为空';
        } else if (!emailRegex.test(formData.email)) {
            newErrors.email = '请输入有效的邮箱地址';
        }

        // 密码验证
        if (!formData.password) {
            newErrors.password = '密码不能为空';
        } else if (formData.password.length < 6) {
            newErrors.password = '密码至少需要6个字符';
        }

        // 确认密码验证
        if (formData.password !== formData.confirmPassword) {
            newErrors.confirmPassword = '两次输入的密码不匹配';
        }

        setErrors(newErrors);
        return Object.keys(newErrors).length === 0;
    };

    // 表单提交
    const handleSubmit = async (e) => {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        setLoading(true);

        try {
            await register(
                formData.username,
                formData.email,
                formData.password
            );

            setNotification({
                open: true,
                message: '注册成功！正在跳转到主页...',
                severity: 'success'
            });

            // 延迟后跳转到主页
            setTimeout(() => {
                navigate('/');
            }, 2000);

        } catch (error) {
            console.error('Registration error:', error);
            let errorMessage = '注册失败';

            if (error.message) {
                errorMessage = error.message;
            }

            setNotification({
                open: true,
                message: errorMessage,
                severity: 'error'
            });
        } finally {
            setLoading(false);
        }
    };

    // 关闭通知
    const handleCloseNotification = () => {
        setNotification({
            ...notification,
            open: false
        });
    };

    return (
        <Container maxWidth="sm">
            <Box
                sx={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    minHeight: '100vh',
                    py: 4
                }}
            >
                <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ duration: 0.5 }}
                >
                    <Typography
                        component="h1"
                        variant="h4"
                        sx={{ mb: 4, fontWeight: 700, textAlign: 'center' }}
                    >
                        创建您的账户
                    </Typography>
                </motion.div>

                <AnimatedCard>
                    <Box component="form" onSubmit={handleSubmit} noValidate>
                        <FormInput
                            label="用户名"
                            name="username"
                            value={formData.username}
                            onChange={handleChange}
                            error={errors.username}
                            icon={<PersonIcon />}
                            autoFocus
                            required
                        />

                        <FormInput
                            label="邮箱地址"
                            name="email"
                            type="email"
                            value={formData.email}
                            onChange={handleChange}
                            error={errors.email}
                            icon={<EmailIcon />}
                            required
                        />

                        <FormInput
                            label="密码"
                            name="password"
                            type="password"
                            value={formData.password}
                            onChange={handleChange}
                            error={errors.password}
                            icon={<LockIcon />}
                            required
                        />

                        <FormInput
                            label="确认密码"
                            name="confirmPassword"
                            type="password"
                            value={formData.confirmPassword}
                            onChange={handleChange}
                            error={errors.confirmPassword}
                            icon={<LockIcon />}
                            required
                        />

                        <Button
                            type="submit"
                            fullWidth
                            disabled={loading || authLoading}
                            sx={{ mt: 2, mb: 3 }}
                        >
                            {loading || authLoading ? '注册中...' : '注册'}
                        </Button>

                        <Grid container justifyContent="center">
                            <Grid item>
                                <Link component={RouterLink} to="/login" variant="body2">
                                    已有账户？点击登录
                                </Link>
                            </Grid>
                        </Grid>
                    </Box>
                </AnimatedCard>
            </Box>

            <Snackbar
                open={notification.open}
                autoHideDuration={6000}
                onClose={handleCloseNotification}
                anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
            >
                <Alert
                    onClose={handleCloseNotification}
                    severity={notification.severity}
                    sx={{ width: '100%' }}
                >
                    {notification.message}
                </Alert>
            </Snackbar>
        </Container>
    );
};

export default Register; 